package com.yjd.comm.system.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.cache.CachedUtil;
import com.yjd.comm.cache.ICachedService;
import com.yjd.comm.news.model.CategoryModel;
import com.yjd.comm.news.service.ICategoryService;
import com.yjd.comm.util.ServiceHolder;

public class CategoryUtill {

	/**
	 * 
	 * 获取缓存Map<catid,model>
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<Long, CategoryModel> getCategorys() throws Exception {
		List<CategoryModel> categoryList = getCategoryList();
		Map<Long, CategoryModel> categorys = new HashMap<Long, CategoryModel>();
		for (CategoryModel m : categoryList) {
			categorys.put(m.getCatid(), m);
		}
		return categorys;
	}

	/**
	 * 
	 * 获取所有缓存列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<CategoryModel> getCategoryList() throws Exception {
		List<CategoryModel> categoryList= (List<CategoryModel>) CachedUtil.defaultCached().get("category");
		if (categoryList == null) {
			categoryList=refreshCache();
		}
		return categoryList;
	}

	/**
	 * 
	 * 根据父级id获取列表
	 * 
	 * @param lid
	 * @return
	 * @throws Exception
	 */
	public static List<CategoryModel> getCategorysByLid(Long lid)
			throws Exception {
		List<CategoryModel> plist= getCategoryList();
		List<CategoryModel> list = new ArrayList<CategoryModel>();
		for (CategoryModel e : plist) {
			if (e.getLid().intValue() == lid.intValue()) {
				list.add(e);
			}
		}
		return list;

	}

	/**
	 * 
	 * 根据ename获取categoryModel
	 * 
	 * @param ename
	 * @return
	 * @throws Exception
	 */
	public static CategoryModel getCategoryByEname(String ename)
			throws Exception {
		List<CategoryModel> plist= getCategoryList();
		for (CategoryModel m : plist) {
			if (m.getEnname().equals(ename))
				return m;
		}
		return null;
	}

	/**
	 * 
	 * 刷新缓存
	 * 
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<CategoryModel> refreshCache() throws Exception {
		ICategoryService service = ServiceHolder.getService(
				ICategoryService.class, "categoryService");
		Map<String, String> parm = new HashMap<String, String>();
		parm.put("sort", "pid ASC");
		List<CategoryModel> categoryList = service.getModelList(parm,DbWREnums.READ);
		CachedUtil.defaultCached().set("category", ICachedService.ONE_DAY, categoryList);
		return categoryList;
	}
}
